package io.github.javpower.imagerex.interceptor;

import io.github.javpower.imagerex.actuator.AccessLogEndpoint;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ApiLogInterceptor implements HandlerInterceptor {

    private final AccessLogEndpoint accessLogEndpoint;

    public ApiLogInterceptor(AccessLogEndpoint accessLogEndpoint) {
        this.accessLogEndpoint = accessLogEndpoint;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();

        if (path.startsWith("/api/") && handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            Operation operation = method.getMethodAnnotation(Operation.class);
            String desc = (operation != null && !operation.summary().isEmpty())
                    ? operation.summary()
                    : path;
            String ip = request.getRemoteAddr();
            int port = request.getRemotePort();
            accessLogEndpoint.addLog(desc,ip,port,path);
        }

        return true;
    }
}